//
//  MPSubmitViewController.m
//  SearchPeople
//
//  Created by jcc on 16/5/6.
//
//

#import "MPSubmitTableViewController.h"
#import "MPImport.h"
#import "MPDocumentHttpClient.h"
#import "RFSegmentView.h"

@interface MPSubmitTableViewController ()
<
UIImagePickerControllerDelegate,
UINavigationControllerDelegate
>

@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *timeTextField;
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UITextField *linkManPhoneTextField;
@property (weak, nonatomic) IBOutlet UITextView *describeTextView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *typeSegmented;

@property (nonatomic) NSInteger selectedIndex;
@property (strong, nonatomic) UIImagePickerController *imagePicker;

@property (copy, nonatomic) NSString *imageUrl;

@end

@implementation MPSubmitTableViewController

#pragma mark - UIViewControler Life Cycle

- (void)viewDidLoad
{
    self.avatarImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(MPshowImagePickerController)];
    [self.avatarImageView addGestureRecognizer:singleTap];
    [self showSegmentControl];
}

#pragma mark - Private method

- (void)showSegmentControl
{
    RFSegmentView *segmentView = [[RFSegmentView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) items:@[@"寻人者",@"发现者"]];
    
    segmentView.tintColor       = CustomTintColor;
    segmentView.selectedIndex   = 0;
    segmentView.itemHeight      = 30.f;
    
    __weak typeof(self) weakSelf = self;
    segmentView.handlder = ^ (RFSegmentView * __nullable view, NSInteger selectedIndex) {
        weakSelf.selectedIndex = selectedIndex;
    };
    
    [self.typeSegmented.superview addSubview:segmentView];
    
    [segmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40);
        make.left.equalTo(weakSelf.typeSegmented.superview.mas_left).offset(0);
        make.right.equalTo(weakSelf.typeSegmented.superview.mas_right).offset(0);
        make.center.equalTo(weakSelf.typeSegmented);
    }];
    self.typeSegmented.hidden = YES;
}

- (void)MPshowImagePickerController
{
    __weak typeof(self) weakSelf = self;
    [UIActionSheet showInView:self.view withTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拍照", @"从相册中选取"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
        if (buttonIndex == 1)
        {
            [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
        }else if (buttonIndex == 0)
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
            }else
            {
                [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
            }
        }
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [SVProgressHUD show];
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    __weak typeof(self) weakSelf = self;
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        weakSelf.avatarImageView.image = image;
        if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            UIImageWriteToSavedPhotosAlbum(image, weakSelf, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        }
        [[MPDocumentHttpClient shareInstance] uploadImage:image
                                         WithSuccessBlock:^(MPRequest *request, MPResponse *response)
         {
             weakSelf.imageUrl = response.errorMsg;
             [SVProgressHUD dismiss];
        } WithFailedBlock:^(MPRequest *request, MPResponse *response)
        {
            [SVProgressHUD dismiss];
        }];
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    NSLog(@"保存图片%@",error != NULL ? @"失败" : @"成功");
}

#pragma mark - Action

- (IBAction)submit:(UIBarButtonItem *)sender
{
    if (!self.imageUrl)
    {
        [SVProgressHUD showErrorWithStatus:@"请添加失踪人照片"];
        return;
    }
    if (self.nameTextField.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入失踪人姓名"];
        return;
    }
    if (self.timeTextField.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入失踪时间"];
        return;
    }
    if (self.addressTextField.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入失踪地点"];
        return;
    }
    if (self.linkManPhoneTextField.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人电话"];
        return;
    }
    if (self.describeTextView.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入失踪人的描述"];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    [[MPDocumentHttpClient shareInstance] CreateDocumentWithType:self.selectedIndex
                                                      WithpicUrl:self.imageUrl
                                                        WithName:self.nameTextField.text
                                                 WithDescription:self.describeTextView.text
                                                        WithTime:self.timeTextField.text
                                                      WithMobile:self.linkManPhoneTextField.text
                                                     WithAddress:self.addressTextField.text
                                                WithSuccessBlock:^(MPRequest *request, MPResponse *response)
     {
        [SVProgressHUD showSuccessWithStatus:@"创建成功"];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } WithFailedBlock:^(MPRequest *request, MPResponse *response)
    {
        
    }];
}

#pragma mark - Getter && Setter

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

@end
